package com.audaque.springboot.foshanupload.security.util;

import cn.hutool.core.bean.BeanUtil;
import com.audaque.springboot.foshanupload.authcore.model.currentUser.TransmittableThreadLocalCurrentUser;
import com.audaque.springboot.foshanupload.security.model.MyGrantedAuthority;
import com.audaque.springboot.foshanupload.security.model.MyUserDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zgb
 * @desc 处理session部分
 * @date 2023-07-13 16:52:37
 */
@Slf4j
public class SecurityContextAuthentication2TransmittableThreadLocalCurrentUserUtil {


    public static void covert() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication instanceof AnonymousAuthenticationToken){
            log.debug("匿名访问:AnonymousAuthenticationToken：针对匿名用户的Token");
            return;
        }
        if(authentication==null){
            return;
        }
        String username = authentication.getName();
        log.debug("username:" + username);
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        log.debug("authorities:" + authorities);
        Object credentials = authentication.getCredentials();
        log.debug("credentials:" + credentials);
        WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
        log.debug("details:" + details);
        MyUserDetail principal = (MyUserDetail)authentication.getPrincipal();
        log.debug("principal:" + principal);
        TransmittableThreadLocalCurrentUser transmittableThreadLocalCurrentUser = new TransmittableThreadLocalCurrentUser();
        transmittableThreadLocalCurrentUser.setId(principal.getId());
        transmittableThreadLocalCurrentUser.setTenantId(principal.getTenantId());
        transmittableThreadLocalCurrentUser.setUsername(principal.getUsername());
        transmittableThreadLocalCurrentUser.setSessionId(details.getSessionId());

        Set<MyGrantedAuthority> authorities1 = principal.getAuthorities();
        List<String> collect = authorities1.stream().map(e -> e.getAuthority()).collect(Collectors.toList());
        transmittableThreadLocalCurrentUser.setAuthority(String.join(",", collect));
        //父子线程传递上下文（用户信息）,  TransmittableThreadLocal，避免重复解析用户
        TransmittableThreadLocalCurrentUser.setCurrentUser(transmittableThreadLocalCurrentUser);

    }


}
